var express = require('express');
var router = express.Router();
var config = require('../config');
var up = require('../db/formidable');
var VandB = require('../db/VandB');
var fs = require('fs');

router.use(function(req, res, next){
	if (!req.infos._id) {
		res.redirect('/log/login')
	} else {
		next()
	}
})

router.post('/', function(req, res, next){
	up.upvideo(req, config.PATH, function(upPath){
		res.json({'videoPath':upPath})
	})
})

router.post('/animeInfo', function(req, res, next){
	console.log(req.body.videoPath)
	var imgname = req.body.videoPath[0]
	imgname = imgname.replace(/.mp4/,'.png');

	var base64Img = req.body.imgPath
	base64Img = base64Img.replace(/^data:image\/\w+;base64,/, "");

	var dataBuffer = new Buffer(base64Img, 'base64')
	fs.writeFile(config.PATH+imgname, dataBuffer, function(err){
		if (err) {
			res.send(err)
		} else {
			req.VandB.insert({
				'type':'anime',
				'pass':false,
				'name':req.body.vName,
				'info':req.body.vInfo,
				'tag' :req.body.tag,
				'path':req.body.videoPath,
				'img' :imgname,
				'upUser'   :req.body.user.userid,
				'upTime'   :new Date().getTime()
			}, function(err, result){
				if (err) {
					
				} else {
					res.send('ok')
				}
			})
		}
	})
})

router.get('/adminivideo/:id', function(req, res, next){
	VandB.findByUpuser(req, 'video', req.params.id, function(itm){
		res.render('./userAdmini/video',{
			'title':'视频管理',
			'user':req.infos,
			'videoList':itm
		})
	})
})


router.delete('/adminivideo', function(req, res, next){
	VandB.delete(req, 'video', req.body.av, req.body.path, function(d){
		res.status(d.status).json(d.d)
	})
})

router.get('/anime', function(req, res, next){
	res.render('./anime/upAnime',{'title':'番剧上传','user':req.infos});
})

module.exports = router;